package nix.bs.web.servlet;

import java.awt.Image;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.ImageIcon;

import nix.bs.domain.Book;
import nix.bs.domain.Category;
import nix.bs.service.BookService;
import nix.bs.service.CategoryService;
import nix.commons.CommonUtils;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase.FileSizeLimitExceededException;
import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class AdminAddBookServlet extends HttpServlet {

	private BookService bookService = new BookService();
	private CategoryService categoryService = new CategoryService();

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");

		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload sfu = new ServletFileUpload(factory);
		sfu.setFileSizeMax(200 * 1024);
		sfu.setSizeMax(300 * 1024);
		try {
			// 普通项
			List<FileItem> fileItemList = sfu.parseRequest(request);
			Map<String, String> map = new HashMap<String, String>();
			for (FileItem fileItem : fileItemList) {
				map.put(fileItem.getFieldName(), fileItem.getString("utf-8"));
			}
			Book book = CommonUtils.toBean(map, Book.class);
			book.setBid(CommonUtils.uuid());
			book.setIsdel(false);
			Category category = CommonUtils.toBean(map, Category.class);
			book.setCategory(category);
			// 文件项
			String savepath = this.getServletContext().getRealPath(
					"/bs/book_img");
			int idxExt = fileItemList.get(1).getName().lastIndexOf(".");
			if (idxExt == -1) {
				request.setAttribute("msg", "上传文件格式不正确！");
				request.setAttribute("categoryList", categoryService.findAll());
				request.getRequestDispatcher("/bs/adminjsps/admin/book/add.jsp")
						.forward(request, response);
				return;
			}
			String extension = fileItemList.get(1).getName().toLowerCase()
					.substring(idxExt + 1);
			if (!extension.equals("jpg") && !extension.equals("png")
					&& !extension.equals("gif")) {
				request.setAttribute("msg", "上传文件格式不正确！（jpg|png|gif）");
				request.setAttribute("categoryList", categoryService.findAll());
				request.getRequestDispatcher("/bs/adminjsps/admin/book/add.jsp")
						.forward(request, response);
				return;
			}
			String filename = CommonUtils.uuid() + "." + extension;
			File destFile = new File(savepath, filename);
			fileItemList.get(1).write(destFile);
			// 校验宽高
			Image image = new ImageIcon(destFile.getAbsolutePath()).getImage();
			if (image.getWidth(null) > 200 || image.getHeight(null) > 300) {
				destFile.delete();
				request.setAttribute("msg", "上传图片尺寸超出限制！（200*300）");
				request.setAttribute("categoryList", categoryService.findAll());
				request.getRequestDispatcher("/bs/adminjsps/admin/book/add.jsp")
						.forward(request, response);
				return;
			}
			// 添加
			book.setImage("book_img/" + filename);
			bookService.add(book);
			// 转发
			request.getRequestDispatcher("/bs/admin/BookServlet?method=findAll")
					.forward(request, response);
		} catch (Exception e) {
			if (e instanceof FileSizeLimitExceededException
					|| e instanceof SizeLimitExceededException) {
				request.setAttribute("msg", "上传文件超出大小！（200K）");
				request.setAttribute("categoryList", categoryService.findAll());
				request.getRequestDispatcher("/bs/adminjsps/admin/book/add.jsp")
						.forward(request, response);
			}
		}
	}
}
